package cn.eastseven.demo.chat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.nio.charset.Charset;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.eastseven.demo.netty.common.NettyMessageDecoder;
import cn.eastseven.demo.netty.common.NettyMessageEncoder;

@Service
public class ChatServer {

	@Autowired
	private Config config;
	
	@Autowired
	private LoginAuthRespHandler loginAuthRespHandler;
	
	@Autowired
	private HeartBeatRespHandler heartBeatRespHandler;
	
	@Autowired
	private BusinessRespHandler businessRespHandler;
	
	public void run() throws Exception {

		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		
		try {
			
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workerGroup);
			b.channel(NioServerSocketChannel.class);
			b.option(ChannelOption.SO_BACKLOG, 1024);
			b.handler(new LoggingHandler(LogLevel.INFO));
			
			b.childHandler(new ChannelInitializer<SocketChannel>() {
				@Override
				protected void initChannel(SocketChannel ch) throws Exception {
					ch.pipeline().addLast(new NettyMessageDecoder(1024 * 1024, 4, 4, -8, 0));  
					ch.pipeline().addLast(new NettyMessageEncoder());
					ch.pipeline().addLast("loginAuthRespHandler", loginAuthRespHandler);
					ch.pipeline().addLast("heartBeatRespHandler", heartBeatRespHandler);
					ch.pipeline().addLast("businessRespHandler",  businessRespHandler);
				}
			});
			
			ChannelFuture f = b.bind(config.getPort()).sync();
			f.channel().closeFuture().sync();
			
		} finally {
			workerGroup.shutdownGracefully();
			bossGroup.shutdownGracefully();
		}
	
	}
	
}
